package com.example.webshiro.common.config;

import cn.hutool.http.server.HttpServerResponse;
import com.example.webshiro.common.response.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @author LuoYu
 * date 2021/2/3
 */
@Slf4j
@ControllerAdvice
public class ControllerExceptionHandler {



    @ExceptionHandler(AuthorizationException.class)
    public ModelAndView authExceptionHandler(AuthorizationException e, HttpServletRequest request){
        ModelAndView view = new ModelAndView();
        if(e instanceof UnauthenticatedException){
            view.setViewName("redirect:/login");
        }else if (e instanceof UnauthorizedException){
            view.setViewName("redirect:/error/401");
        }
        return view;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public void controllerMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServerResponse response){
        response.sendError(500,"参数错误");
        response.setAttr("data",ResponseData.error("参数错误"));
    }











}
